package com.beici.waterghost.controller;


import com.beici.waterghost.model.resultes;
import com.beici.waterghost.model.user;
import com.beici.waterghost.service.impl.ablumServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.Properties;

@RestController
@RequestMapping("/email")
@CrossOrigin
public class emailController {

    @PostMapping("/send")
    public resultes send(String content,String value,String method){
        user principal = (user) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //创建一个配置文件并保存
        Properties properties = new Properties();
        properties.setProperty("mail.host", "smtp.qq.com");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");
        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("746381864@qq.com", "授权密钥");
            }
        });
        //获取连接对象
        Transport transport = null;
        try {
            transport = session.getTransport();
            //连接服务器
            transport.connect("smtp.qq.com", "746381864@qq.com", "bkdgmhvptozlbega");
            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage(session);
            //邮件发送人
            mimeMessage.setFrom(new InternetAddress("746381864@qq.com"));
            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("746381864@qq.com"));
            //邮件标题
            mimeMessage.setSubject("来自:"+principal.getUserId()+"的"+value);
            //邮件内容
            mimeMessage.setContent("申请区块："+value+"<br>详细信息："+content+"<br> 联系方式:"+method, "text/html;charset=UTF-8");
            //发送邮件
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            return resultes.success("发送成功",null);
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        return resultes.error("发送失败");

    }



}
